// var express = require('express');
// var ajaxData = require('./ajaxData');
// var app = express();
// var ajaxData = new ajaxData(); 
// app.use(express.static('public'));

// app.get('/', function (req, res) {
//   console.log("主页 GET 请求");
//   res.sendFile( __dirname + "index.html" );
// })

// //list 页面 GET 请求
// app.get('/list', function (req, res) {
//   console.log("/list GET 请求");
//   res.sendFile( __dirname + "/public/" + "list.html" );
// })

// //返回json数据
// app.get('/json',function(req,res,next){   //#返回json  
//   res.json(ajaxData.datajson);  
// }); 

// var server = app.listen(3000, function () {
//   var host = server.address().address;
//   var port = server.address().port;
//   console.log("应用实例，访问地址为 http://127.0.0.1", host, port);
// })

var express = require('express');
var fs = require('fs');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var getLogin = require('./getLoginInfo');
var loginData = require('./json/login.json');//加载登录json数据
var ajaxData = require('./json/ajaxData.json');//加载ajax json数据
var app = express();
var getLogin = new getLogin(); 

app.use(express.static('public'));//设置静态文件路径
app.use(cookieParser('sessiontest'));
app.use(session({
  secret: 'sessiontest',//与cookieParser中的一致
  resave: true,
  saveUninitialized: true
}));

//登录页面 GET 请求
app.get('/', function (req, res) {
  console.log("主页 GET 请求");
  console.log(req.session.user);
  if (req.session.user) {
    var user = req.session.user;
    var name = user.name;
    res.redirect("list.html");
  } else {
    console.log('您还没有登录，请先登录再试，谢谢！');
    //res.redirect("login.html");
    res.sendFile( __dirname + "/public/" + "login.html" );
  }
});

//index页面 GET 请求
app.get('/list', function (req, res) {
  console.log('cao:', req.session.user);
  if (req.session.user) {
    var user = req.session.user;
    var name = user.name;
    res.sendFile( __dirname + "/public/" + "list.html");
  } else {
    console.log('您还没有登录，请先登录再试，谢谢');
    res.redirect(301, "login.html");
    //res.sendFile( __dirname + "/public/" + "login.html" );
  }
});

//登录模块
app.get('/login.json', function (req, res, next) {  
  var userInfo = loginData.user;
  var name = req.query.name;
  var password = req.query.password;
  //参数处理 get请求用req.query   post请求用req.body
  if (name == userInfo[name].name && password == userInfo[name].password) {
    //设置用户session
    var user = {name: name};
    req.session.user = user;
    res.json({success: true, message: "登录成功"});
  } else {
    res.json({success: false, message: "登录失败，用户名或者密码错误"});
  }
});

//列表数据
app.get('/list.json',function(req, res, next){
  res.json(ajaxData);  
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log("应用实例，访问地址为 http://127.0.0.1", host, port);
});
